// 网络配置和错误处理工具
import { fetch as tauriFetch } from '@tauri-apps/plugin-http';
import { getVersion } from '@tauri-apps/api/app';

// 检测 Tauri 环境
export async function isTauriEnvironment() {
  try {
    await getVersion();
    return true;
  } catch {
    return false;
  }
}

// 网络请求配置
export const NetworkConfig = {
  // API 基础配置
  API_BASE_URL: 'https://api.jisuapi.com/caipiao',
  API_KEY: '92d6b37e3b476a14',
  TIMEOUT: 30000, // 30秒超时
  
  // 重试配置
  MAX_RETRIES: 3,
  RETRY_DELAY: 1000, // 1秒
  
  // 请求头配置
  getHeaders: (isTauri = false) => ({
    'Accept': 'application/json, text/plain, */*',
    'Content-Type': 'application/json',
    ...(isTauri && {
      'User-Agent': 'Mozilla/5.0 (Linux; Android 10; Mobile) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Mobile Safari/537.36'
    })
  }),
  
  // URL 转换（Web环境下使用代理）
  transformUrl: (url, isTauri = false) => {
    if (!isTauri && /^https?:\/\/api\.jisuapi\.com\/.*/i.test(url)) {
      return url.replace(/^https?:\/\/api\.jisuapi\.com/i, '/api');
    }
    return url;
  }
};

// 统一的网络请求函数
export async function makeRequest(url, options = {}) {
  const isTauri = await isTauriEnvironment();
  
  const config = {
    method: options.method || 'GET',
    headers: NetworkConfig.getHeaders(isTauri),
    timeout: options.timeout || NetworkConfig.TIMEOUT,
    ...options
  };
  
  const finalUrl = NetworkConfig.transformUrl(url, isTauri);
  
  console.log(`[网络请求] 环境: ${isTauri ? 'Tauri' : 'Web'}, URL: ${finalUrl}`);
  
  let lastError;
  
  // 重试机制
  for (let attempt = 1; attempt <= NetworkConfig.MAX_RETRIES; attempt++) {
    try {
      let response;
      
      if (isTauri) {
        // Tauri 环境
        response = await tauriFetch(finalUrl, {
          method: config.method,
          headers: config.headers,
          timeout: config.timeout / 1000, // Tauri 使用秒
          body: config.body
        });
        
        if (!response.ok) {
          throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        
        const data = response.data;
        return typeof data === 'string' ? JSON.parse(data) : data;
        
      } else {
        // Web 环境
        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), config.timeout);
        
        try {
          response = await fetch(finalUrl, {
            ...config,
            signal: controller.signal,
            mode: 'cors',
            credentials: 'omit'
          });
          
          clearTimeout(timeoutId);
          
          if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
          }
          
          const text = await response.text();
          if (!text.trim()) {
            throw new Error('服务器返回空响应');
          }
          
          return JSON.parse(text);
          
        } catch (error) {
          clearTimeout(timeoutId);
          throw error;
        }
      }
      
    } catch (error) {
      lastError = error;
      console.warn(`[网络请求] 第 ${attempt} 次尝试失败:`, error.message);
      
      // 如果不是最后一次尝试，等待后重试
      if (attempt < NetworkConfig.MAX_RETRIES) {
        await new Promise(resolve => setTimeout(resolve, NetworkConfig.RETRY_DELAY * attempt));
      }
    }
  }
  
  // 所有重试都失败了
  throw createFriendlyError(lastError, finalUrl, isTauri);
}

// 创建用户友好的错误信息
function createFriendlyError(error, url, isTauri) {
  let message = '网络请求失败';
  let suggestions = [];
  
  if (!navigator.onLine) {
    message = '网络连接不可用';
    suggestions.push('请检查网络连接');
  } else if (error?.name === 'AbortError') {
    message = '请求超时';
    suggestions.push('请检查网络速度', '稍后重试');
  } else if (error?.message?.includes('CORS') || error?.message?.includes('fetch')) {
    message = '跨域请求被阻止';
    suggestions.push('确保代理服务器正常运行', '检查 setupProxy.js 配置');
  } else if (error?.message?.includes('JSON')) {
    message = 'API 响应格式错误';
    suggestions.push('API 服务可能异常', '尝试使用模拟数据');
  } else if (error?.status >= 400 && error?.status < 500) {
    message = `客户端错误 (${error.status})`;
    suggestions.push('检查 API 密钥配置', '确认请求参数正确');
  } else if (error?.status >= 500) {
    message = `服务器错误 (${error.status})`;
    suggestions.push('API 服务暂时不可用', '稍后重试');
  }
  
  const friendlyError = new Error(`${message}: ${error?.message || '未知错误'}`);
  friendlyError.originalError = error;
  friendlyError.suggestions = suggestions;
  friendlyError.environment = isTauri ? 'Tauri' : 'Web';
  friendlyError.url = url;
  
  return friendlyError;
}

// 网络诊断工具
export async function runNetworkDiagnosis() {
  const results = {
    timestamp: new Date().toISOString(),
    environment: await isTauriEnvironment() ? 'Tauri' : 'Web',
    tests: []
  };
  
  // 测试 1: 基本网络连接
  try {
    const testUrl = 'https://httpbin.org/get';
    await makeRequest(testUrl, { timeout: 5000 });
    results.tests.push({
      name: '基本网络连接',
      status: '成功',
      message: '可以访问外部 API'
    });
  } catch (error) {
    results.tests.push({
      name: '基本网络连接',
      status: '失败',
      message: error.message,
      suggestions: error.suggestions
    });
  }
  
  // 测试 2: 目标 API 连接
  try {
    const apiUrl = `${NetworkConfig.API_BASE_URL}/class?appkey=${NetworkConfig.API_KEY}`;
    await makeRequest(apiUrl, { timeout: 10000 });
    results.tests.push({
      name: '目标 API 连接',
      status: '成功',
      message: '可以访问极速数据 API'
    });
  } catch (error) {
    results.tests.push({
      name: '目标 API 连接',
      status: '失败',
      message: error.message,
      suggestions: error.suggestions
    });
  }
  
  return results;
}